<template>
    <div>
        <div class="address" @click="toaddr">收货地址：{{address}}</div>
        <div class="empty" v-if="carts.length === 0">
            购物车空空如也，快去挑选商品吧！
        </div> 
        <div class="noempty" v-else>
            <div class="carts">
                <div class="delete"  @click='delAll()'><van-button round type="danger" >删除</van-button></div>
                <van-card
                    v-for="cart in carts"
                    :key="cart.id"
                    :num="cart.number"
                    :desc="cart.specs"
                    >
                    <template #thumb>
                        <van-checkbox @change="checkOne()" v-model="cart.checked"></van-checkbox>
                        <img :src="cart.banner" />
                    </template>
                    <template #title>
                        <b>{{cart.name}}</b>
                    </template>
                    <template #price>
                        <span style="color: red;">￥{{cart.price}}</span>
                    </template>
                    <template #num>
                        <van-button @click="reduceNum(cart.id)" round size="mini" plain type="info">-</van-button>
                        <span class="pronum">{{cart.number}}</span>
                        <van-button @click="addNum(cart.id)" round size="mini" type="danger">+</van-button>
                    </template>
                    
                    <template #bottom>
                        <br>
                        小计： <span>￥{{cart.subtotal}}</span>
                    </template>
                    <template #price-top>
                        <span @click="del(cart.id)" class="remove">×</span>
                    </template>
                </van-card>
            </div>

            <div class="jiesuan">
            <div class="settle">
                <van-checkbox @click="checkedAll()" v-model="checkAll" checked-color="#fff">全选</van-checkbox>
                <div class="text">
                    <p>实付：￥{{totalPrice}}</p>  
                    <p>已优惠：￥6</p>
                </div>
                <van-button round plain>去结算（{{totalNum}}）</van-button>
            </div>
        </div>
        </div>
        
    </div>
</template>

<script>
import {getCookie} from '@/utils/cookie'
import {getCartsPro,editCart,delCart,getDefaultAddr,removeChecked} from '@/request'
import Vue from 'vue';
import { Card } from 'vant';
import { Checkbox, CheckboxGroup } from 'vant';
import { Button } from 'vant';
import {operate} from '@/utils/math'
import { Dialog } from 'vant';
import { Toast } from 'vant';

Vue.use(Toast);
Vue.use(Button);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Card);
export default {
    data(){
        return{
            carts:[],
            checkAll: false,
            address:''
        }
    },
    created(){
        var username = getCookie('username')
        if(!username){
            Toast.fail('请先登录再查看购物车吧！')
            localStorage.setItem('url','/cart')
            this.$router.push('/my/login')
        }
        getCartsPro().then(data =>{
            this.carts = data.map(item =>{
                item.checked = false
                item.subtotal = operate(item.price,item.number,'*')
                return item
            })
        })
        getDefaultAddr().then(data =>{
            //请求回来的数据属性太多，作整理
            if(data.code ===1){
                this.address = data.data.name+','+data.data.tel+','+data.data.address
            }else{
                this.address ='请移步添加地址'
            }
        })
    },
    computed:{
        //这里的key表示我们要在页面中使用的数据名称
        //这里的value，是一个函数，用于写计算的代码，  --用return返回结果
        totalPrice(){
            //先找到所有被选中的商品
            var carts = this.carts.filter(item =>item.checked)
            var n = 0
            carts.forEach(item =>{
                n += item.subtotal      //遍历，然后计算所有商品价格
            })
            return n
        },
        //这里totalPrice函数，在html中作为元素来使用，不加(),和data中的数据使用一样

        totalNum(){
            var carts = this.carts.filter(item => item.checked)
            var n = 0
            carts.forEach(item => n += item.number)
            return n         //计算总商品数量
        }
    },
    methods:{
        addNum(id){
            //根据当前商品id，从所有商品中获取到这个商品
            var cart = this.carts.find(item => item.id ===id)
            cart.number++
            cart.subtotal = operate(cart.price, cart.number, '*')
            // console.log(cart.number)
            //在这里的数据发生了变化，也就是carts里的数据发生了变化，进行双向绑定的页面也会变化
            editCart(cart).then(data =>{
                console.log(data);
            })
        },
        reduceNum(id){
            var cart = this.carts.find(item => item.id ===id)
            //当数量变为0时，直接将商品删除
            cart.number--
            if(cart.number === 0){
                var index = this.carts.findIndex(item => item.id === id)
                //根据下标删除
                this.carts.splice(index,1)
                delCart(id).then(data =>{
                    
                })
            }else{
                cart.subtotal = operate(cart.price, cart.number, '*')
                editCart(cart).then(data =>{
                console.log(data);
            })
            }
        },
        checkedAll(){
            //全选框
            this.carts.forEach(item =>{
                item.checked = this.checkAll
            })
        },
        checkOne(){
            //判断每个商品是否都被选中，判断carts里每个对象的checked是否都为true
            //用数组的every方法遍历
            this.checkAll = this.carts.every(item =>item.checked)
        },
        del(id){
            Dialog.confirm({
                title:'购物车删除',
                message:'您确定要删除该商品吗？',
            })
                .then(()=>{
                    //确认删除时
                    //先删除carts里的商品，在向data.json发送删除数据请求
                    //用数组的splice方法（开始下标，删除个数）去删除
                    var index = this.carts.findIndex(item => item.id === id)
                    this.carts.splice(index,1)

                    //调用函数，发送删除请求
                    delCart(id).then(data => {
                        Toast.success('data.msg')
                    })

                })
                .catch(()=>{
                    //取消操作，不删除时
                    Toast.success('已取消！')
                });
        },
        delAll(){

        Dialog.confirm({
            title: '删除',
            message: '你确定删除所选购物车吗？',
            })
            .then(() => {
                // 要删除所有被选中的商品
                // 先获取所有选中的商品
                var checkedData = this.carts.filter(item => item.checked)
                // 发起批量删除的请求
                removeChecked(checkedData).then(data => {
                    Toast.success('已删除')
                    getCartsPro().then(data => {
                    this.carts = data.map(item => {
                    item.checked = false
                    item.subtotal = operate(item.price, item.number, '*')
                    return item
                    })
                    })
                })
            })
            .catch(() => {
                // on cancel
                 Toast.success('已取消！');
            });
    },
        toaddr(){
            //跳转到地址页面
            this.$router.push('/address')
        }
    }
}
</script>

<style>
.address{
    padding: 10px 20px;
    text-align: center;
    border-bottom: 2px solid #ccc;
}
.addresss{
    margin: 20px 20px;
    padding: 0 10px;
    text-align: left;
}
.delete{
    padding: 0px 30px;
    text-align: right;
    background-color:rgba(153, 153, 153, 0.048) ;
}
.carts img{
width: 80px;
height: 100px;
margin-left: 40px;
}
.carts .van-checkbox{
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
}
.van-card__thumb{
width: 130px;
}
.van-card__num .van-button{
width: 20px;
height: 20px;
font-size: 18px;
vertical-align: top;
}
.pronum{
margin: 0 10px;
font-size: 16px;
}
.van-card__content>div:first-child{
margin-right: 75px;
}
.van-card__num{
margin-right: 25px;
}
.remove{
position: absolute;
top: 15%;
transform: translateY(-50%);
right: 0;
font-size: 40px;
padding: 10px;
}
.jiesuan{
position: fixed;
bottom: 50px;
left: 0;
width: 100%;
background-color: #f00;
}
.settle{
display: flex;
justify-content: space-between;
padding: 10px 20px;
align-items: center;
color: #fff;
}
.settle .van-checkbox__label{
color: #fff;
}
.settle .text{
flex: 1;
padding-left: 20px;
}
.settle .text p{
padding: 0;
margin: 0;
}
.van-card{
    text-align: left;
}
</style>